import {getUserInfo} from "../../../utils/http";
import {getDicts} from "../../../api/common";
import {updateInfo, attrConfList} from "../../../api/um";
import {getAge} from "../../../utils/util";

const globalData = getApp().globalData;
const {colorOption, config, userInfo} = globalData;
const maxTime = new Date(new Date().getFullYear() - 20, 11, 31).getTime();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    colorOption,
    userInfo,
    attrDataMap: userInfo.attrDataMap,
    tabActive: 0,
    localImgSrc: config.localImgSrc,
    currentDate: maxTime,
    maxDate: maxTime,
    autosize: {
      maxHeight: 200,
      minHeight: 120,
    },
    // 是否显示下一步按钮
    isShowNextButton: false,
    // 字典Map
    dictMap: {},
    // 当前字典
    curDict: {},
    // 当前key
    curKey: {},
    // 展示字典Map
    showDictMap: {},
    // 表单数据
    formData: {},
    attrConfMap: {},
    completeness: '',
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 是否显示下一步按钮
    const {
      isShowNextButton = false
    } = options;
    this.setData({
      isShowNextButton
    })
    this.refreshUserInfo();
    // 下拉组件
    this.selectCom = this.selectComponent("#selectCom");
    // 多选组件
    this.checkboxCom = this.selectComponent("#checkboxCom");
    // 日期组件
    this.dateSelectCom = this.selectComponent("#dateSelectCom");
    this.attrConfList();
  },
  attrConfList() {
    attrConfList(res => {
      let attrConfMap = {};
      res.data.forEach(item => {
        attrConfMap[item.attrType] = attrConfMap[item.attrType] || [];
        attrConfMap[item.attrType].push(item);
      });
      this.setData({
        attrConfMap
      })
      this.getDicts(res.data)
      this.calcCompleteness();
    })
  },
  refreshUserInfo() {
    getUserInfo(() => {
      const {
        userInfo
      } = globalData;
      const {
        attrDataMap = {}
      } = userInfo;
      attrDataMap.XC_list = attrDataMap.XC ? attrDataMap.XC.split(',') : []
      this.setData({
        userInfo,
        attrDataMap
      })
      this.calcCompleteness();
    })
  },
  calcCompleteness() {
    const {
      attrConfMap,
      attrDataMap
    } = this.data;
    if (!attrConfMap.base || !attrDataMap) {
      return;
    }
    const attrList = attrConfMap.base.concat(attrConfMap.detail).concat(attrConfMap.sign)
    let total = attrList.length;
    let num = 0;
    attrList.forEach(attr => {
      if (attrDataMap[attr.attrCode] && attrDataMap[attr.attrCode].length) {
        num++;
      }
    })
    this.setData({
      completeness: (num / total * 100).toFixed(0)
    })
  },
  // 获取字典
  getDicts(confList) {
    const {
      dictMap
    } = this.data
    const dictTemp = {}
    const dictTypes = []
    confList.forEach(item => {
      if (item.dictType) {
        dictTypes.push(item.dictType)
      }
    })

    getDicts({
      data: {
        key: dictTypes.join(",")
      },
      callBack: res => {
        res.data.forEach(dict => {
          if (dictTemp[dict.dictType]) {
            dictTemp[dict.dictType].push(dict)
          } else {
            dictTemp[dict.dictType] = [dict];
          }
        })
        confList.forEach(conf => {
          if (conf.dictType && dictTemp[conf.dictType]) {
            dictMap[conf.attrCode] = {
              title: conf.attrName,
              key: conf.attrCode,
              dictType: conf.dictType,
              index: 0,
              columns: dictTemp[conf.dictType].map(item => {
                return {
                  label: item.dictLabel,
                  value: item.dictValue
                }
              }),
            }
          }
        })
        this.setData({
          dictMap
        })
      }
    })
  },
  // 切换tab前
  onTabBeforeChange(e) {
    const {
      callback
    } = e.detail;
    const {
      isShowNextButton
    } = this.data;
    if (isShowNextButton) callback(true);
    else callback(true);
  },

  // 切换tab
  onTabChange(e) {
    const {
      index: tabActive
    } = e.detail;
    this.setData({
      tabActive,
    });
  },

  // 上传头像完成
  handleAvatar(e) {
    const {
      detail: fileList
    } = e;
    const {
      attrDataMap
    } = this.data
    attrDataMap.TX = fileList[0]
    this.setData({
      attrDataMap
    })
  },

  // 上传相册完成
  handlePhoto(e) {
    const {
      attrDataMap
    } = this.data
    const {
      detail: fileList
    } = e;
    attrDataMap.XC_list = fileList
    attrDataMap.XC = fileList.join(",")
    this.setData({
      attrDataMap
    })
  },

  // 输入框变化
  onInputChange(e) {
    const key = e.currentTarget.dataset.key;
    const detail = e.detail;
    this.setData({
      [`attrDataMap.${key}`]: detail,
    });
    this.calcCompleteness();
  },
  onInputChange2(e) {
    const key = e.currentTarget.dataset.key;
    const detail = e.detail;
    this.setData({
      [`attrDataMap.${key}`]: detail.value,
    });
    this.calcCompleteness();
  },

  // 点击下拉
  handleShowSelect(e) {
    const {key} = e.currentTarget.dataset;
    const {dictMap, attrDataMap} = this.data;
    const curDict = dictMap[key];
    curDict.columns.forEach((s, i) => {
      if (s.value == attrDataMap[key]) {
        curDict.index = i;
      }
    })
    if (curDict) {
      this.setData({
        curDict,
      });
      this.selectCom.onShow();
    }
  },
  handleShowSelectNumber(e) {
    const {key, title} = e.currentTarget.dataset;
    const curValue = this.data.attrDataMap[key];
    let minIndex = 0;
    let maxIndex = 0;
    if (curValue) {
      minIndex = curValue[0] - 1;
      maxIndex = curValue[1] - 1;
    } else {
      if (key === 'condition-NL') {
        minIndex = 19;
        maxIndex = 19;
      } else if (key === 'condition-TZ') {
        minIndex = 49;
        maxIndex = 49;
      } else if (key === 'condition-SG') {
        minIndex = 159;
        maxIndex = 159;
      }
    }
    const nums = Array.from({length: 999}, (v, k) => k + 1);

    const curDict = {
      title: title,
      key,
      columns: [{
        values: nums,
        className: 'column-min',
        defaultIndex: minIndex,
      },
        {
          values: nums,
          className: 'column-max',
          defaultIndex: maxIndex,
        },],
    }
    this.setData({
      curDict,
    });
    this.selectCom.onShow();

  },


  // 确定下拉值
  handleConfirmSelect(e) {
    const {
      index,
      value: data
    } = e.detail;
    const {
      curDict
    } = this.data;
    console.log("选中的值index", index);
    console.log("选中的值", data);
    console.log("当前下拉配置", curDict);
    if (index instanceof Array) {
      this.setData({
        [`attrDataMap.${curDict.key}`]: data,
        [`attrDataMap.${curDict.key}_str`]: data.join('-'),
      });
    } else {
      this.setData({
        [`dictMap.${curDict.key}.index`]: index,
        [`attrDataMap.${curDict.key}`]: data.value,
        [`attrDataMap.${curDict.key}_str`]: data.label,
      });
    }
    this.calcCompleteness();
  },

  // 打开选择生日
  onShowSelectBrithday(e) {
    const {
      key
    } = e.currentTarget.dataset;
    let {
      attrDataMap,
      currentDate
    } = this.data;
    let date = attrDataMap[key]
    currentDate = date ? new Date(date).getTime() : maxTime;
    this.setData({
      currentDate,
      curKey: key,
    });
    this.dateSelectCom.onShow();
  },

  // 确定选择生日
  onConfirmBirthday(e) {
    const data = e.detail;
    const {
      curKey,
      attrDataMap
    } = this.data;
    attrDataMap[curKey] = data;
    if (curKey === 'SR' && data) {
      attrDataMap.NL = getAge(data)
    }
    this.setData({
      attrDataMap
    });
    this.calcCompleteness();
  },

  // 点击多选框
  handleShowCheckbox(e) {
    const {
      key
    } = e.currentTarget.dataset;
    const {
      dictMap
    } = this.data;
    const curDict = dictMap[key];
    if (curDict) {
      this.setData({
        curDict,
      });
      this.checkboxCom.onShow();
      this.checkboxCom.setValue(this.data.attrDataMap[key]);
    }
  },
  // 确定多选值
  handleConfirmCheckbox(e) {
    const value = e.detail;
    const {
      curDict
    } = this.data;
    this.setData({
      [`attrDataMap.${curDict.key}`]: value,
      [`attrDataMap.${curDict.key}_str`]: curDict.columns.filter(s => value.indexOf(s.value) > -1).map(s => s.label).join('丨'),
    });
    this.calcCompleteness();
  },
  // 下一步 保存提交
  nextStep() {
    const {
      tabActive,
      isShowNextButton,
      userInfo,
      attrDataMap
    } = this.data;
    if (!isShowNextButton || tabActive === 2) {
      wx.showLoading({
        title: '保存中',
      })
      updateInfo({
        data: {
          ...userInfo,
          attrDataMap
        },
        callBack: res => {
          this.refreshUserInfo();
          wx.hideLoading()
          wx.showToast({
            title: '保存成功',
          })
          setTimeout(() => wx.navigateBack(), 1000);
        }
      })
    } else {
      this.setData({
        tabActive: tabActive + 1,
      });
    }
  },
  goBack() {
    wx.navigateBack()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
  },
});